package com.easy.util;

import cn.hutool.crypto.digest.DigestUtil;

public class PasswordUtil {
    private final static char[] arr={'a','b','c','d','e','f','0','1','2','3','4','5','6','7','8','9'};
    private static final int salt_index = 4;
    private static final int count_index =15;
    public static String getEncryption(String password){
        //随机盐值
        int index_salt=(int)(Math.random()* arr.length);
        char salt = arr[index_salt];
        //随机加密数
        int index_count=(int)(Math.random()* arr.length);
        char count = arr[index_count];
        String encryptionPassword=password+salt;
        for(int i=0;i<count;i++){
            encryptionPassword=DigestUtil.md5Hex(encryptionPassword);
//            System.out.println(encryptionPassword);
        }
        StringBuilder strb=new StringBuilder(encryptionPassword);
//        System.out.println(encryptionPassword);
        strb.insert(salt_index,salt);
        strb.insert(count_index,count);
//        System.out.println(strb);
        return strb.toString();
    }
    public static boolean checkPassword(String password,String encryptionPassword){
        char salt = encryptionPassword.charAt(salt_index);
        char count = encryptionPassword.charAt(count_index);
        String decode = password+salt;
        for(int i=0;i<count;i++){
            decode=DigestUtil.md5Hex(decode);
//            System.out.println(encryptionPassword);
        }
        StringBuilder strb=new StringBuilder(decode);
        strb.insert(salt_index,salt);
        strb.insert(count_index,count);
        System.out.println(strb);
        return strb.toString().equals(encryptionPassword);

    }

    public static void main(String[] args) {
        System.out.println(getEncryption("123456"));
        System.out.println(checkPassword("123456","502fedbb5a8243ee1048b271caad3f1560"));
    }
}
